package org.cyk.demo1;

import javax.swing.text.html.Option;
import java.util.List;
import java.util.Optional;

public class Solution {

//    public void test1() {
//        List<String> helloWorld = Optional.ofNullable("hello world").stream().toList();
//        System.out.println(helloWorld.size());
//        for(String str : helloWorld) {
//            System.out.println(str);
//        }
//    }

    public void test1() {
        //创建一个空的 Optional
        Optional<Object> empty = Optional.empty();

        //创建非空的 Optional
        Student student1 = new Student();
        Optional<Student> os1 = Optional.of(student1);

        //创建一个空的 Optional
        Student student2 = null;
        Optional<Student> os2 = Optional.of(student2);
    }

    public void test2() {
        //ifPresent 无参使用: 判断 os1 中是否有值
        Student student = new Student();
        Optional<Student> os1 = Optional.of(student);
        System.out.println(os1.isPresent()); //true

        //ifPresent 有参使用: 若 student 对象不为空，则对该对象进行赋值，并打印一句话
        os1.ifPresent(aa -> { //此处的 aa 就代指 student
            aa.setName("cyk");
            aa.setAge(20);
            System.out.println("个人信息已初始化: " + student);
        });
    }

    public void test3() throws Exception {
        //get 获取空对象，报错
        Student student = null;
        Optional<Student> os1 = Optional.ofNullable(student);
        Student student1 = os1.get(); //此处抛出异常: java.util.NoSuchElementException: No value present

        //如果 student 为空，就返回一个新对象
        Student student2 = os1.orElse(new Student());

        //如果 student 为空，就调用我们自己实现的函数
        Student student3 = os1.orElseGet(() -> new Student());

        //如果 student 为空，就抛出我们指定的异常
        os1.orElseThrow(() -> new Exception("自定义异常"));
    }

    public void test4() {
        Student student = new Student("cyk", 20);
        Optional<Student> os1 = Optional.ofNullable(student);
        os1.filter(aa -> aa.getName().equals("cyk")) //此处 aa 代指 student
                .ifPresent(result -> System.out.println("ok!"));
    }

    public void test5() {
        Student student = new Student("cyk", 20);
        Optional<Student> os1 = Optional.ofNullable(student);
        //如果 os1 中存在值，就执行 lambda 表达式，如果不存在值，就返回一个空的 Optional
        Optional<Student> result = os1.map(aa -> {
            aa.setAge(aa.getAge() + 1);
            return aa;
        });
        System.out.println(result); //输出: Optional[Student(name=cyk, age=21)]
    }


    public static void main(String[] args) throws Exception {
        Solution solution = new Solution();
        solution.test5();

    }

}
